package com.mymarkdown.app.fx.event.hander.impl;

import cn.hutool.core.util.ObjectUtil;
import com.mymarkdown.app.fx.annotation.KeyWord;
import com.mymarkdown.app.fx.enums.FxEventEnum;
import com.mymarkdown.app.fx.event.hander.KeyWordHandler;
import com.mymarkdown.app.fx.event.hander.MenuHandler;
import com.mymarkdown.app.fx.event.model.FxEvent;
import com.mymarkdown.app.interfaces.UserInfoService;
import com.mymarkdown.app.util.FileChooserUtil;
import com.mymarkdown.app.websocket.enums.MessageTypeEnum;
import com.mymarkdown.app.websocket.interfaces.WebSocketSendMessage;
import com.mymarkdown.app.websocket.message.MessagePojo;
import com.mymarkdown.app.websocket.interfaces.SaveFileMenu;
import javafx.scene.web.WebEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.*;
import java.util.concurrent.BlockingQueue;

/**
 * @author zenglun
 * @date 2021/12/5 9:59 上午
 * @description: 保存相关的处理
 */
@Slf4j
@KeyWord(FxEventEnum.SAVE_MD)
@Component("saveFileMenuHandlerImpl")
public class SaveFileMenuHandlerImpl implements MenuHandler, SaveFileMenu, KeyWordHandler {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private WebSocketSendMessage webSocketSendMessage;

    /**
     * 推送消息给客户端，如果客户端接受到了消息，则会调用http接口，传送md数据，并弹出对话框
     *
     * @param engine
     * @param event
     */
    @Override
    public void handler(WebEngine engine, FxEvent event) {

        //发送完消息之后,等待用户
        BlockingQueue<File> operationFile = userInfoService.getOperationFile();
        File peek = operationFile.peek();
        if (Objects.isNull(peek)) {
            showSaveDialog();
        }
        //发送消息给Session
        if (ObjectUtil.isNotNull(operationFile.peek())){
            MessagePojo messagePojo = new MessagePojo();
            messagePojo.setMessageType(MessageTypeEnum.SAVE_MD_BODY.getMessageType());
            messagePojo.setMsgId(UUID.randomUUID().toString());
            webSocketSendMessage.sendMessage(messagePojo);
        }
    }

    @Override
    public boolean afterHandler(WebEngine engine, FxEvent event) {
        return true;
    }

    @Override
    public void beforeHandler(WebEngine engine, FxEvent event) {

    }


    @Override
    public void showSaveDialog() {
        FileChooserUtil.showSaveDialog(file -> {
            try {
                //填充file数据
                userInfoService.getOperationFile().put(file);
            } catch (InterruptedException e) {
                log.error("[SaveFileMenuHandlerImpl]---[showSaveDialog],存储当前操作文件被中断,异常信息为:{}", e);
            }
        }, "markdown", "*.md");
    }
}
